from scipy import misc
import tensorflow as tf
import align.detect_face as detect_face
import cv2
import time;
import json
from MyEncoder import MyEncoder

class face_service:
    minsize = 20 # minimum size of face
    threshold = [ 0.6, 0.7, 0.7 ]  # three steps's threshold
    factor = 0.709 # scale factor
    gpu_memory_fraction=1.0

    def __init__(self):
        with tf.Graph().as_default(): #创建 tensorflow session
            gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=self.gpu_memory_fraction)
            sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False))
            with sess.as_default():
                self.pnet, self.rnet, self.onet = detect_face.create_mtcnn(sess, None)

    def detect_face(self, img):
        bounding_boxes, _ = detect_face.detect_face(img, self.minsize, self.pnet, self.rnet, self.onet, self.threshold, self.factor)
        nrof_faces = bounding_boxes.shape[0]#人脸数目
        print('找到人脸数目为：{}'.format(nrof_faces))

        boxes = [] #转化为数组
        for face_position in bounding_boxes:
            face_position=face_position.astype(int)
            boxes.append([face_position[0], face_position[1],face_position[2], face_position[3]]);
        return nrof_faces, boxes;

    def _get_img(self, image_path):
        cap = cv2.VideoCapture(image_path)
        if(cap.isOpened()) :
            ret,img = cap.read();
            return img;

        return None;

    def image_save(self, img, bounding_boxes, new_img_path):
            for face_position in bounding_boxes:
                print(face_position);
                cv2.rectangle(img, (face_position[0], face_position[1]), (face_position[2], face_position[3]), (0, 255, 0), 2)
            cv2.imwrite(new_img_path, img);
            return new_img_path;


if __name__ == '__main__':
    service = face_service();
    img = service._get_img("http://oper-img-18.oss-cn-beijing.aliyuncs.com/1537336949685678/70.jpg");
    nrof_faces, bounding_boxes = service.detect_face(img);

    img_path = str(int(time.time())) + ".jpg";
    service.image_save(img, bounding_boxes, img_path);

    result_data = {"nrof_faces": 0, "bounding_boxes": "", "img_path": ""};
    # 组装数据返回
    result_data['nrof_faces'] = nrof_faces;
    result_data['bounding_boxes'] = bounding_boxes;

    print(result_data);
    str = json.dumps(result_data, cls=MyEncoder);

